<?php


namespace EchoPHP\Database\Connectors;


use PDO;

class MysqlConnector extends Connector implements ConnectorInterface {

    /**
     * 简历mysql连接
     * @param array $config
     * @return PDO
     */
    public function connect(array $config) {
        //解析PDO连接所需参数
        $dsn = $this->getDsn($config);
        $userName = $config['username'] ?? '';
        $password = $config['password'] ?? '';
        $options = $config['options'] ?? [];

        $this->addDefaultOptions([
            PDO::ATTR_EMULATE_PREPARES => false,            //禁用预处理模拟
        ]);
        $options = $this->getOptions($options);

        $connection = $this->createConnection($dsn, $userName, $password, $options);

        return $connection;
    }

    /**
     * 获取连接dsn
     * @param array $config
     * @return string
     */
    protected function getDsn(array $config) {
        if (isset($config['socket']) && !empty($config['socket'])) {
            $dsn = 'mysql:unix_socket=' . $config['socket'];
        } elseif (isset($config['port']) && !empty($config['port'])) {
            $dsn = 'mysql:host=' . $config['host'] . ';port=' . $config['port'];
        } else {
            $dsn = 'mysql:host=' . $config['host'];
        }
        $dsn .= ';dbname=' . $config['database'];

        if (isset($config['charset']) && !empty($config['charset'])) {
            $dsn .= ';charset=' . $config['charset'];
        }

        return $dsn;
    }

}